<?php
declare (strict_types=1);

namespace app\admin\model\advertiser;

use app\admin\model\base\User;
use app\BaseModel;

/**
 * 广告主推广任务日志记录表
 */
class AdvertiserTaskLog extends BaseModel
{
    /**
     * 获取公众号推广任务明细记录
     * @param array $where
     * @param int $page
     * @param int $limit
     * @param string $orderby
     * @return array
     */
    public static function getList(array $where, int $page, int $limit, string $orderby = ''): array
    {
        $data = self::alias('a')
            ->field('a.*,b.task_name,c.unionid,c.nickname,c.avatar,c.sex')
            ->where($where)
            ->leftJoin((new AdvertiserTask)->getTable() . ' b', 'b.id = a.task_id')
            ->leftJoin((new User())->getTable() . ' c', 'c.id = a.user_id')
            ->order($orderby)
            ->paginate(['list_rows' => $limit, 'page' => $page], false)
            ->toArray();
        return $data;
    }

    /**
     * 写入公众号推广任务明细记录
     * @param int $user_id
     * @param string $mac_id
     * @param int $task_id
     * @param float $single_price
     * @return bool
     */
    public static function writeTaskLog(int $user_id, string $mac_id, int $task_id, float $single_price): bool
    {
        //临时更新完成量(次)和花费(元)
        AdvertiserTask::where('id', $task_id)
            ->inc('complete', 1)
            ->inc('total_price', $single_price)
            ->update();
        //临时更新广告主余额和总花费
        AdvertiserUser::where('id', $user_id)
            ->dec('balance', $single_price)
            ->inc('total_price', $single_price)
            ->update();
        //写入明细记录
        $log['task_id'] = $task_id;
        $log['user_id'] = $user_id;
        $log['type'] = 1;
        $log['mac_id'] = $mac_id;
        $log['price'] = $single_price;
        $log['create_time'] = time();
        self::insertGetId($log);
        return true;
    }

}




